# -*- coding: utf-8 -*-
'''     Server API for yellow wave on android
        Do an tot nghiep Nguyen Hong Giang
'''
import cherrypy
import simplejson as json
import math
from pymongo import Connection
from pymongo.objectid import ObjectId

MONGO_SERVER = "localhost"
MONGO_PORT = 27017
SONGVANGDB = 'songvang'

class BackEndAPI():
    __categories = {'yte': 'yte', 'quanan': 'nhahangquanan', 'taichinh': 'tuvanmoigioi',
                    'dulich': 'khachsandulich', 'thoitrang': 'lamdepspa', 'khachsan': 'khachsandulich',
                    'giaitri': 'nghethuatgiaitri', 'lamdep': 'lamdepspa'}
    
    @cherrypy.expose
    def index(self):
        return 'backend songvang api'
    
    @cherrypy.expose
    def listregion(self):
        return json.dumps([{'id': 'Hà Nội', 'name': 'Hà Nội'}, {'id': 'TP Hồ Chí Minh', 'name': 'TP Hồ Chí Minh'}, 
                           {'id': 'Đà Nẵng', 'name': 'Đà Nẵng'}, {'id': 'Quảng Ninh', 'name': 'Quảng Ninh'}, 
                           {'id': 'Huế', 'name': 'Huế'}, {'id': 'Cần Thơ', 'name': 'Cần Thơ'}, 
                           {'id': 'Đồng Nai', 'name': 'Đồng Nai'}, {'id': 'Hải Phòng', 'name': 'Hải Phòng'},
                           {'id': 'Vũng Tàu', 'name': 'Vũng Tàu'}, {'id': 'Khánh Hòa', 'name': 'Khánh Hòa'}, 
                           {'id': 'Bình Dương', 'name': 'Bình Dương'}])
    
    @cherrypy.expose
    def main(self, cat, region='', search='', page=1, pageSize=10):
        connection = Connection(MONGO_SERVER, MONGO_PORT)
        db = connection[SONGVANGDB]
        collection = db[self.__categories[cat]]
        condition = {}
        if region != '': condition['city'] = region
        numberOfRows = collection.find(condition).count()
        numberOfPages = int(math.ceil(float(numberOfRows) / pageSize))
        if page < 1: page = 1
        start = (page - 1) * pageSize
        rows = collection.find(condition).skip(start).limit(pageSize)
        diadiemData = []
        for r in rows:
            diadiemData.append({'ten': r['shopName'], 'dienthoai': r['phone'], 'id': r['_id']})
        return json.dumps({'diadiems': diadiemData, 'page': page, 'pages': numberOfPages})
    
    @cherrypy.expose
    def detail(self, id):
        connection = Connection(MONGO_SERVER, MONGO_PORT)
        db = connection[SONGVANGDB]
        print id
        result = None
        for cat in self.__categories.values():
            collection = db[cat]
            result = collection.find_one({'_id': ObjectId(id)})
            connection.end_request()
            if result: break
        if result != None:
            data = {'ten': result['shopName'], 'diachi': result['address'], 'dienthoai': result['phone'], 'images': len(result['images'])}
            for i in range(len(result['images'])):
                data['image{0}'.format(i)] = {'type': '', 'url': result['images'][i]}
            return json.dumps(data)
        return {}
        
    
if __name__ == '__main__':
    _cp_config = {'tools.gzip.on': True}
    global_conf = {
        'global': {
        'server.socket_host': '0.0.0.0',
        'server.socket_port': 8888,
        'tools.encode.on': True,
        'tools.encode.encoding': 'UTF-8'
        },
    }
    cherrypy.config.update(global_conf)
    cherrypy.quickstart(BackEndAPI())